import React, { useState, ReactNode } from "react";
import { useQueryStr, checkAuth } from "utils/help";
import { Menu } from "antd";
import { MenuType } from "type/menu";
import { PieChartOutlined, UsergroupAddOutlined } from "@ant-design/icons";
import { Link, useLocation } from "react-router-dom";
const { SubMenu } = Menu;

export default function MenuPage() {
  const [openKeys, setOpenKeys] = useState<string[]>([]);
  const pathnName = useLocation().pathname;
  const useRouteType = () => {
    const menu = useQueryStr("menu");
    if (menu) {
      return [menu];
    }
    let result = [];
    const list = pathnName.split("/");
    list.shift();
    result = list;

    if (!isNaN(Number(result[result.length - 1]))) {
      result.pop();
    }
    return result;
  };

  const routeType = useRouteType();

  const menuList: Array<MenuType> = [
    {
      key: "database",
      value: "数据库",
      icon: <PieChartOutlined />,
      children: [
        {
          key: "list",
          value: "数据列表",
          path: "/list",
        },
      ],
    },
    {
      key: "user",
      value: "用户管理",
      icon: <UsergroupAddOutlined />,
      children: [
        {
          key: "account",
          value: "个人中心",
          path: "/user/account",
        },
        {
          key: "member",
          value: "成员管理",
          path: "/user/member",
          authority: ["admin", "user"],
        },
      ],
    },
  ];

  const renderMenu = (list: Array<MenuType>) => {
    let result: Array<ReactNode> = [];
    list.forEach((menu) => {
      if (menu.children && menu.children.length) {
        result.push(
          <SubMenu key={menu.key} icon={menu.icon} title={menu.value}>
            {renderMenu(menu.children)}
          </SubMenu>
        );
      } else {
        result.push(
          <Menu.Item key={menu.key}>
            <Link
              to={{
                pathname: menu.path,
              }}
            >
              {menu.icon}
              {menu.value}
            </Link>
          </Menu.Item>
        );
      }
    });
    return result;
  };

  return (
    <Menu
      style={{ width: 200 }}
      openKeys={openKeys}
      selectedKeys={routeType}
      mode="inline"
      onOpenChange={(openKeys: React.Key[]) => {
        if (
          openKeys[0] === "tasks" &&
          openKeys.length <= 2 &&
          openKeys[1] === "type"
        ) {
          setOpenKeys(openKeys as string[]);
        } else {
          const key = [...openKeys].pop() || "";
          setOpenKeys([key] as string[]);
        }
      }}
    >
      {renderMenu(checkAuth(menuList))}
    </Menu>
  );
}
